package com.violet.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtTokenUtil {

    // 密钥
    private final static String KEY_WORD = "supermarket_violet_flower_2024/12/14";
    // 过期时间, 单位：秒
    private final static long EXPIRE_TIME = 60 * 60 * 24 * 7;

    public static String generateToken(String userId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        Date now = new Date();
        Date expire = new Date(now.getTime() + EXPIRE_TIME * 1000);

        // 生成 Token
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(now)
                .setExpiration(expire)
                .signWith(Keys.hmacShaKeyFor(KEY_WORD.getBytes()), SignatureAlgorithm.HS256)
                .compact();
    }

    public static Claims parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(Keys.hmacShaKeyFor(KEY_WORD.getBytes()))
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

}
